//
//  SearchViewController.m
//  Delicious2
//
//  Created by dllo on 16/1/11.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchResultViewController.h"
@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
//搜索类
@property (nonatomic, strong) UISearchBar *search;

@property (nonatomic, strong) UITableView *tableView;
//历史记录数组
@property (nonatomic, strong) NSMutableArray *historyDataSource;
//热搜数组
@property (nonatomic, strong) NSArray *searchDataSource;

@property (nonatomic, strong) MBProgressHUD *HUD;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
//    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"ImageLeftBack"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(leftBackButtonDidPress:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    //搜索初始化
    self.search = [[UISearchBar alloc] initWithFrame:CGRectMake(40, 26, self.view.frame.size.width - 40, 30)];
    self.search.delegate = self;
    self.search.showsCancelButton = YES;
    self.search.searchBarStyle = UISearchBarStyleMinimal;
    self.search.placeholder = @" 搜索你感兴趣的内容";
    [self.navigationController.view addSubview:self.search];
    
    //历史记录数组
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"historyDataSource"]) {
        self.historyDataSource = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"historyDataSource"]];
    } else {
        self.historyDataSource = [NSMutableArray arrayWithCapacity:0];
    }
    

    
    [self creatTableView];
    [self getData];
}

#pragma mark - creatTableView
- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.userInteractionEnabled = YES;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    
    [self.view addSubview:self.tableView];
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.historyDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UITableViewCellIdentifier"];
    
    if (self.historyDataSource.count) {
        cell.textLabel.text = self.historyDataSource[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:@"ImageTime"];
    }
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [self.search resignFirstResponder];
    //跳转搜索结果界面
    SearchResultViewController *resultVC = [[SearchResultViewController alloc] init];
    resultVC.strQ = self.historyDataSource[indexPath.row];
    [self.navigationController pushViewController:resultVC animated:YES];
    
    [self.historyDataSource exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
    [self.tableView reloadData];

}

//分区头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 2, 30)];
    label.text = @"历史记录";
    
    UIButton *buttonDelete = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonDelete setBackgroundImage:[UIImage imageNamed:@"ImageDelete"] forState:UIControlStateNormal];
    buttonDelete.frame = CGRectMake(self.view.frame.size.width - 60, 0, 30, 30);
    [buttonDelete addTarget:self action:@selector(buttonDelegteDidPress:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:label];
    [headerView addSubview:buttonDelete];
    //如果有历史记录则显示分区否则不显示
    if (self.historyDataSource.count) {
        return headerView;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.historyDataSource.count) {
        return 30;
    } else {
        return CGFLOAT_MIN;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.search resignFirstResponder];
}

//热搜按钮
- (void)settableViowFooterView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 220)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
    label.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    label.text = @"大家都在搜";
    
    UILabel *labelLine = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 - 0.5, 60, 1, 160)];
    labelLine.backgroundColor = [UIColor blackColor];
    labelLine.alpha = 0.2;
 
    //    设置热搜按钮
    for (int i = 0; i < 10; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.titleLabel.textAlignment = 1;
        button.titleLabel.text = self.searchDataSource[i];
        [button setTitle:self.searchDataSource[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchUpInside];
        if (i % 2 == 0) {
            button.frame = CGRectMake(0, 20 * (i + 1) + 20, WIDTH / 2, 30);
        } else {
            button.frame = CGRectMake(WIDTH / 2, 20 * i + 20, WIDTH / 2, 30);
        }
        [view addSubview:button];
    }
    [view addSubview:labelLine];
    [view addSubview:label];
    self.tableView.tableFooterView = view;
}



#pragma mark - 获取数据
- (void)getData {
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载";
    [FSDNetWorkTool getWithURL:@"http://food.boohee.com/fb/v1/keywords" withParameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {

        self.searchDataSource = [NSMutableArray arrayWithArray:result[@"keywords"]];
        
        [self settableViowFooterView];
        [self.tableView reloadData];
        self.HUD.hidden = YES;
    } fail:^(NSError *error) {
        NSLog(@"错误");
        self.HUD.labelText = @"加载失败";
        [self.HUD hide:YES afterDelay:3];
    }];
}


#pragma maek - searchBar打理方法
//搜索按钮点击
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [self.historyDataSource insertObject:searchBar.text atIndex:0];
    [self.tableView reloadData];
    [self.search resignFirstResponder];
    //跳转结果页面
    SearchResultViewController *resultVC = [[SearchResultViewController alloc] init];
    resultVC.strQ = searchBar.text;
    [self.navigationController pushViewController:resultVC animated:YES];
    
}

//取消按钮
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.search resignFirstResponder];
    [self.search endEditing:YES];
    
}

#pragma mark - 左侧返回按钮点击事件
- (void)leftBackButtonDidPress:(UIButton *)button {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.search resignFirstResponder];
}
//热搜按钮点击事件
- (void)buttonDidPress:(UIButton *)button {
    [self.historyDataSource insertObject:button.titleLabel.text atIndex:0];
    [self.tableView reloadData];
    [self.search resignFirstResponder];
    
    SearchResultViewController *resultVC = [[SearchResultViewController alloc] init];
    resultVC.strQ = button.titleLabel.text;
    [self.navigationController pushViewController:resultVC animated:YES];
    
}
//清除历史记录按钮点击事件
- (void)buttonDelegteDidPress:(UIButton *)button {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要删除历史记录?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
}
//提示框方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex) {
        [self.historyDataSource removeAllObjects];
        [self.tableView reloadData];
        alertView.hidden = YES;
    }
}

//页面消失存本地 
- (void)viewWillDisappear:(BOOL)animated {
    self.search.hidden = YES;
    [[NSUserDefaults standardUserDefaults] setObject:self.historyDataSource forKey:@"historyDataSource"];
}

- (void)viewWillAppear:(BOOL)animated {
    if (self.search) {
        self.search.hidden = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
